import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import axios from 'axios'
export default class index extends Component {
  search = () => {
    const {value} = this.keywordInput
    // 通知views更新状态
    // this.props.updateAppState({isFirst: false, isLoading: true})
    axios.get(`https://api.github.com/search/users?q=${value}`).then(res => {
      // 通知List更新状态 发布消息
      const data = {isLoading:false, users:res.data.items, isFirst: false}
      PubSub.publish('listStateChange', data)
      // this.props.updateAppState({isLoading:false, users:res.data.items, isFirst: false})
    }).catch(err => {
      const data = {isLoading:false, err:'查询出错', isFirst: false}
      PubSub.publish('listStateChange', data)
      // this.props.updateAppState({isLoading:false, err:'查询出错', isFirst: false})
    })
  }
  fetchSearch = async () => {
    const {value} = this.keywordInput
    // fetch关注分离思想 使用Promise链式调用
    // fetch(`https://api.github.com/search/users?q=${value}`).then(res => {
    //   console.log('联系服务器成功了');
    //   return res.json()
    // }).then(res => {
    //   console.log('获取数据成功了');
    //   const data = {isLoading:false, users:res.items, isFirst: false}
    //   PubSub.publish('listStateChange', data)
    // })
    // .catch(err => {
    //   const data = {isLoading:false, err:'请求出错', isFirst: false}
    //   PubSub.publish('listStateChange', data)
    // })
    // 通过async/await优化
    try {
      const res = await fetch(`https://api.github.com/search/users?q=${value}`)
      const data = await res.json()
      const passState = {isLoading:false, users:data.items, isFirst: false}
      PubSub.publish('listStateChange', passState)
    } catch (err) {
      PubSub.publish('listStateChange', {isLoading:false, err:'请求出错', isFirst: false})
    }
  }
  render() {
    return (
      <div>
        <section className="jumbotron">
          <h3 className="jumbotron-heading search-header">搜索 Github 用户</h3>
          <div className="input-group">
            <input ref={c => this.keywordInput = c} type="text" className="form-control" placeholder="输入关键词点击搜索"/>
            <span className="input-group-btn">
              <button onClick={this.search} className="btn btn-default" type="button">搜索</button>
              <button onClick={this.fetchSearch} className="btn btn-default" type="button">fetch搜索</button>
            </span>
          </div>
        </section>
      </div>
    )
  }
}
